package com.cal.utms.dao.maintenance;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.HolidayCalendar;
import com.cal.utms.util.HibernateUtil;

public class HolidayDaoImpl implements HolidayDao {

	@Override
	public short saveHoliday(List<HolidayCalendar> calendars) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		short result = 0;
		try {
			tx = session.beginTransaction();
			session.createQuery("DELETE FROM HolidayCalendar");
			for (HolidayCalendar holidayCalendar : calendars) {
				session.merge(holidayCalendar);
			}
			tx.commit();
			result = 1;
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		} finally {
			session.close();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<HolidayCalendar> getHolidays() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<HolidayCalendar> calendars = null;
		try {
			tx = session.beginTransaction();
			calendars = session.createQuery("from HolidayCalendar H").list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return calendars;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<HolidayCalendar> getBankHolidays() {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<HolidayCalendar> calendars = null;
		try {
			tx = session.beginTransaction();
			calendars = session.createQuery("from HolidayCalendar H where H.bank= true").list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return calendars;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<HolidayCalendar> getHolidayByYearMonth(int year, int month) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<HolidayCalendar> calendars = null;
		try {
			tx = session.beginTransaction();
			calendars = session.createQuery("from HolidayCalendar H where H.bank= true and month(date)=:mon and year(date)=:yer").setParameter("mon", month)
					.setParameter("yer", year).list();
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return calendars;
	}

}
